import React, { useState, useEffect, useRef } from "react";
import { Card, message, Switch, Modal } from "antd";
import {
  XHbutton,
  XHmodal,
  XHoperate,
  XHtable,
  XHselectForm,
} from "@/components/xh-components/index";
import FormData from "./form";
import { history, connect } from "umi";
import {
  GetListAPI,
  UpdateStatusAPI,
  AddDataAPI,
  DelDataAPI,
  GetViewAPI,
  EditDataAPI,
  dataScopeSApi,
} from "@/api/system/role.ts";
const { confirm } = Modal;

const RolePage = (props) => {
  const { dispatch } = props;
  //查询参数
  const [selectList, setSelectList] = useState([{ label: "创建时间", type: "日期范围" }]);

  // 表格枚举
  const columns = [
    {
      title: "角色编号",
      dataIndex: "roleCode",
      key: "roleCode",
    },

    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
    },
    {
      title: "角色描述",
      dataIndex: "roleDescription",
      key: "roleDescription",
    },

    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (_, record) => {
        return (
          <Switch
            checked={record.status === "0"}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            defaultChecked
            onClick={() => showChangeStatusConfirm(record)}
          />
        );
      },
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    },
    {
      title: "创建人",
      dataIndex: "createBy",
      key: "createBy",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      render: (val) => {
        return (
          <XHoperate
            list={[
              {
                label: "修改",
                emit: () => editDic(val),
              },
              {
                label: "分配用户",
                emit: () => authUser(val),
              },
              {
                label: "数据权限",
                emit: () => datascope(val),
              },
              {
                label: "删除",
                danger: true,
                showMsg: true,
                emit: () => del(val),
              },
            ]}
          />
        );
      },
    },
  ];
  // 表单ref
  const formRef = useRef(null);

  //单挑数据
  const [dataForm, setDataForm] = useState({});

  // 各种状态
  const [state, setState] = useState({
    loading: false,
    show: false,
    title: "新增",
    btnLoading: false,
    total: 0,
  });

  // 列表参数
  const [query, setQuery] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  // 表格数据
  const [tableData, setTableData] = useState({
    data: [],
    total: 0,
  });

  //新增弹窗
  const add = () => {
    setState({
      ...state,
      show: true,
      title: "新增",
    });
  };

  //修改弹窗
  const editDic = async (val) => {
    try {
      dispatch({
        type: "appConfig/loading",
      });
      const { data: res } = await GetViewAPI(val.roleId);

      setDataForm(res);
      setState({
        ...state,
        show: true,
        title: "修改",
      });
    } catch (err) {
      console.log(err);
    } finally {
      dispatch({
        type: "appConfig/closeLoading",
      });
    }
  };

  //关闭弹窗
  const close = () => {
    setDataForm({}); //清空表单
    setState({
      ...state,
      show: false,
    });
  };

  //判断title执行事件
  const Sub = () => {
    if (state.title == "新增") addSub();
    if (state.title == "修改") addSub();
    if (state.title == "数据权限") dataScopeSub();
  };

  //新增确认
  const addSub = async () => {
    const res = await formRef.current.validateFields();
    if (!res) return;
    try {
      setState({
        ...state,
        btnLoading: true,
      });
      await AddDataAPI(res);
      message.success("新增成功!");
      close();
      getList();
    } catch (err) {
      setState({
        ...state,
        btnLoading: false,
      });
    } finally {
    }
  };

  // 修改确认
  const editSub = async () => {
    const res = await formRef.current.validateFields();
    if (!res) return;
    try {
      setState({
        ...state,
        btnLoading: true,
      });
      await EditDataAPI(res);
      message.success("修改成功!");
      close();
      getList();
    } catch (err) {
    } finally {
      setState({
        ...state,
        btnLoading: false,
      });
    }
  };

  //分配数据权限确认
  const dataScopeSub = async () => {
    const res = await formRef.current.validateFields();
    if (!res) return;
    try {
      setState({
        ...state,
        btnLoading: true,
      });
      await dataScopeSApi(res);
      message.success("分配成功!");
      close();
      getList();
    } catch (err) {
    } finally {
      setState({
        ...state,
        btnLoading: false,
      });
    }
  };

  //删除
  const del = async (val) => {
    try {
      DelDataAPI(val.roleId).then((resp) => {
        message.success("删除成功！");
        getList();
      });
    } catch (error) {}
  };

  //改变状态时
  const showChangeStatusConfirm = async (record) => {
    let text = record.status == "1" ? "启用" : "停用";
    const newStatus = record.status == "0" ? "1" : "0";
    confirm({
      centered: true,
      cancelText: "取消",
      okText: "确定",
      title: `确认要${text}${record.roleName}角色吗？`,
      onOk() {
        UpdateStatusAPI({ roleId: record.roleId, status: newStatus }).then((resp) => {
          if (resp.code === 200) {
            message.success(`${text}成功!`);
            getList();
          }
        });
      },
    });
  };

  //分配用户
  const authUser = (val) => {
    history.push(`/system/role-auth/user?id=${val.roleId}`);
  };

  //分页改变时
  const onShowSizeChange = (current, pageSize) => {
    setQuery({ pageNum: current, pageSize: pageSize });
  };

  //分页改变时
  const totalonChange = (current, pageSize) => {
    setQuery({ pageNum: current, pageSize: pageSize });
  };

  //数据权限弹窗
  const datascope = async (val) => {
    try {
      dispatch({
        type: "appConfig/loading",
      });
      const { data: res } = await GetViewAPI(val.roleId);
      setDataForm(res);
      setState({
        ...state,
        show: true,
        title: "数据权限",
      });
    } catch (err) {
      console.log(err);
    } finally {
      dispatch({
        type: "appConfig/closeLoading",
      });
    }
  };

  //查询
  const selectSubmit = (val) => {
    console.log(val, "val");
  };

  //重置
  const selectReset = (val) => {
    console.log(val, "val");
  };

  // 获取表格数据
  const getList = async () => {
    try {
      setState({
        loading: true,
      });
      const res = await GetListAPI(query);
      setTableData({
        data: res.rows,
        total: res.total,
      });
    } catch (err) {
      console.log(err);
    } finally {
      setState({
        loading: false,
      });
    }
  };

  return (
    <div>
      <div>
        <Card>
          <XHselectForm
            list={[
              { label: "测试输入框", type: "输入框", model: "name" },
              { label: "测试时间", type: "时间日期", model: "time" },
            ]}
            selectSubmit={selectSubmit}
          />
          <XHbutton
            list={[
              {
                label: "新增",
                emit: () => add(),
              },
            ]}
          />
          <XHtable
            loading={state.loading}
            columns={columns}
            rowSelection={null}
            dataSource={tableData.data}
            total={tableData.total}
            pagination={(val) => {
              getList({
                ...query,
                ...val,
              });
            }}
          />
          {/* <Table
            bordered={true}
            scroll={{
              x: "calc(700px + 50%)",
              y: 650,
            }}
            rowClassName={{
              align: "center",
            }}
            loading={state.loading}
            dataSource={tableData.data}
            columns={columns}
            pagination={false}
            rowKey={(record, index) => index + 1}
          />
          <Pagination
            showSizeChanger
            showQuickJumper
            onShowSizeChange={onShowSizeChange}
            onChange={totalonChange}
            defaultCurrent={1}
            total={state.total}
          /> */}
        </Card>
        <XHmodal
          open={state.show}
          title={state.title}
          loading={state.btnLoading}
          width={700}
          ok={() => Sub()}
          no={() => close()}
          body={<FormData ref={formRef} data={dataForm} title={state.title} />}
        />
      </div>
    </div>
  );
};
export default connect((state) => ({ user: state.user }))(RolePage);
